import sys

# 解决服务器端找不到模块路径的问题  这块填项linux 部署项目的根目录
sys.path.append('/opt/project/idcard')

from flask import Flask, request, jsonify, render_template, make_response
import com.haojiangbo.handler.IdCardRead as IdCardRead
import com.haojiangbo.handler.ImagePreHander as ImagePreHander
import com.haojiangbo.handler.IdcardRangge as IdcardRange

# flask 官方文档
# https://flask.palletsprojects.com/en/0.12.x/quickstart/#
app = Flask(__name__)
app.config['JSON_AS_ASCII'] = False

# 模型路径
# 模型下载地址
# 链接：https://pan.baidu.com/s/1yR8xBLr-Pw5QiYVRboMAIA
# 提取码：1234
# 字符识别模型
modelPath = "/opt/model"

# 目标检测模型
objectDetection = "model/model8.tflite"

carNoDetection = "model/carNoModel.tflite"

# 初始化身份证识别模型  模型下载地址
idCardHaner = IdCardRead.IdCardReadHander(modelPath, isDebuger=False)

# 图片预处理
imagePreHander = ImagePreHander.ImagePreHander(isDebuger=False)

# 定位身份证区域
idcardRange = IdcardRange.IdcardRange(objectDetection, isDebuger=False)

# 车牌区域定位
carNoRange = IdcardRange.IdcardRange(carNoDetection, isDebuger=False)

# 根据路径识别
# 127.0.0.1:8888/idc/path
@app.route('/idc/path', methods=['POST'])
def idcPath():
    print("request.path = {}".format(request.form['path']))
    str = idCardHaner.predictByPath(request.form['path'])
    data = {'result': str, 'msg': '操作成功', 'code': 200}
    # json.dumps(data).encode()
    return jsonify(data)


# 根据上传文件识别
# 127.0.0.1:8888/idc/file
@app.route('/idc/file', methods=['POST'])
def idcFile():
    f = request.files['file']
    str = idCardHaner.predictByFile(f)
    data = {'result': str, 'msg': '操作成功', 'code': 200}
    return jsonify(data)


# 根据上传文件识别
# 127.0.0.1:8888/idc/img
@app.route('/idc/img', methods=['POST'])
def idcImg():
    f = request.files['file']
    result, resultImg = imagePreHander.predByFile(f)
    str = ""
    if resultImg is not None:
        str = idCardHaner.predictByImg(resultImg, isCoverGary=False)
        print("read str = {}".format(str))

    data = {'result': result, 'msg': '操作成功', 'code': 200, "idcardNo": str}
    return jsonify(data)


# 身份证区域识别
# 127.0.0.1:8888/idc/range
@app.route('/idc/range', methods=['POST'])
def idcRange():
    f = request.files['file']
    min_score_thresh = 0.5
    boxes, classes, scores, xyList, resultImg, imgName = idcardRange.predictByImg(f, min_score_thresh)
    tmpStr = ""
    if resultImg is not None:
        tmpStr = idCardHaner.predictByImg(resultImg, isCoverGary=True)
        print("read str = {}".format(tmpStr))

    # b = json.dumps(.tolist())
    if boxes is not None and len(boxes) > 0 and scores[0] > min_score_thresh:
        data = {'scores': str(scores[0]),
                'idcardNo': tmpStr,
                'boxes': boxes[0].tolist(),
                'result': xyList,
                'msg': '操作成功',
                'imgUrl': request.host_url + imgName,
                'code': 200}
    else:
        data = {'msg': '未检测到数据', 'code': 201}
    return jsonify(data)



# 车牌区域定位
# 127.0.0.1:8888/car/range
@app.route('/car/range', methods=['POST'])
def carRange():
    f = request.files['file']
    min_score_thresh = 0.7
    boxes, classes, scores, xyList, resultImg, imgName = carNoRange.predictByImg(f, min_score_thresh)
    tmpStr = ""
    # if resultImg is not None:
    #     tmpStr = idCardHaner.predictByImg(resultImg, isCoverGary=True)
    #     print("read str = {}".format(tmpStr))

    # b = json.dumps(.tolist())
    if boxes is not None and len(boxes) > 0 and scores[0] > min_score_thresh:
        data = {'scores': str(scores[0]),
                'carNo': tmpStr,
                'boxes': boxes[0].tolist(),
                'result': xyList,
                'msg': '操作成功',
                'imgUrl': request.host_url + imgName,
                'code': 200}
    else:
        data = {'msg': '未检测到数据', 'code': 201}
    return jsonify(data)



@app.route('/<string:filename>', methods=['GET'])
def display_img(filename):
    if request.method == 'GET':
        if filename is None:
            pass
        else:
            image_data = open("/tmp/" + filename, "rb").read()
            response = make_response(image_data)
            response.headers['Content-Type'] = 'image/jpg'
            return response
    else:
        pass


if __name__ == '__main__':
    app.run(host="0.0.0.0", port=8888, debug=False)
